package com.trxy.controller.back;

import com.google.code.kaptcha.Constants;
import com.trxy.model.User;
import com.trxy.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;

@Controller
@RequestMapping("/back")
public class UserLoginController {
    @Autowired
    UserService userService;

    @RequestMapping("/login")
    String login(Integer error,Model model) {
        System.out.println ("错误"+error);
        if (error==null){
            return "back/login/view";
        }else if (error==2){
            model.addAttribute ("error","没有此用户");
            return "back/login/view";
        }else if (error==3){
            model.addAttribute ("error","密码错误");
            return "back/login/view";
        }else if (error==1) {
            model.addAttribute ("error","验证码错误");
            return "back/login/view";
        }
        return "back/login/view";
    }

    //@PostMapping("/dologin")
    @RequestMapping(value = "/dologin", method = RequestMethod.POST)
    String dologin(HttpServletRequest request, String name, String password, String code, HttpSession session,Model model) {

        //验kaptcha
        String kaptcha = (String) session.getAttribute(Constants.KAPTCHA_SESSION_KEY);
        if (!code.equals(kaptcha)) {
            return "redirect:/back/login?error="+1;
        }

        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(name, password);
        try {
            subject.login(token);
        } catch (UnknownAccountException e) {
            e.printStackTrace();
            System.out.println("没有此用户");
            return "redirect:/back/login?error="+2;//重定向回  登录页
        } catch (AuthenticationException e) {
            e.printStackTrace();
            System.out.println("密码错误");
            return "redirect:/back/login?error="+3;//重定向回  登录页
        }

        User user = userService.selectByNameAndPassword(name, password);
        System.out.println ("state"+user.getState ());
        //加入到session
        if (user.getState ().equals ("禁用")){
            model.addAttribute ("state","您已经被禁用");
            return "back/login/error";
        }else {

            request.getSession().setAttribute("USER", user);
            return "redirect:/back/center/index";//重定向到 后台管理页
        }
    }
}
